from fastapi import HTTPException
from starlette import status

from dto import ApiResponse
from model.all_models import UserModel
from utils import enc_util, jwt_util


async def login(username: str, password: str) -> ApiResponse:

    user = await UserModel.get_or_none(username=username)

    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户不存在")

    checked = enc_util.check_password(password, user.password)

    print(f"pwd = {password}, has pwd = {user.password}")
    if not checked:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="密码错误")

    return ApiResponse.success(
        data={
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "token": jwt_util.create_token({
                "id": user.id,
                "username": user.username,
                "email": user.email
            })
        }
    )


async def register_user(username: str, password: str, email: str):

    user = await UserModel.get_or_none(username=username)

    if user:
        raise HTTPException(status_code=401, detail=f"{username} already exists")

    pwd = enc_util.hash_password(password)
    user = await UserModel.create(
        username=username,
        password=pwd,
        email=email
    )

    return user



